package com.ruoyi.ma.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ma.domain.vo.MaMaterialPlanDataDetailsReturnVo;
import com.ruoyi.ma.domain.vo.MaMaterialPlanDetailsExportVo;
import com.ruoyi.ma.domain.vo.MaMaterialPlanDetailsVo;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckLogin;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ma.domain.vo.MaMaterialPlanVo;
import com.ruoyi.ma.domain.bo.MaMaterialPlanBo;
import com.ruoyi.ma.service.IMaMaterialPlanService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 材料计划
 *
 * @author llb
 * @date 2024-11-01
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/ma/materialPlan")
public class MaMaterialPlanController extends BaseController {

    private final IMaMaterialPlanService iMaMaterialPlanService;

    /**
     * 查询材料计划列表
     */
    @SaCheckLogin
    @GetMapping("/list")
    public TableDataInfo<MaMaterialPlanVo> list(MaMaterialPlanBo bo, PageQuery pageQuery) {
        return iMaMaterialPlanService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出材料计划列表
     */
    @SaCheckLogin
    @Log(title = "材料计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MaMaterialPlanBo bo) {
//        List<MaMaterialPlanVo> list = iMaMaterialPlanService.queryList(bo);
//        ExcelUtil.exportExcel(list, "材料计划", MaMaterialPlanVo.class, response);
        List<MaMaterialPlanDetailsVo> detailList = new ArrayList<>();
        String deptName = null;
        String weaveDate = null;
        String htdName = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (bo.getPlanId() != null) {
            MaMaterialPlanDataDetailsReturnVo returnVo = iMaMaterialPlanService.getDetails(bo.getPlanId());
            deptName = returnVo.getInfoData().getDeptName(); // 供应商名称
            Date date = returnVo.getInfoData().getWeaveDate();
            if (ObjectUtils.isNotEmpty(date)) {
                weaveDate = sdf.format(date); // 编制日期
            }
            String bdName = null;
            String zdName = null;
            // 合同段拼接=标段-站点
            bdName = StringUtils.isBlank(returnVo.getInfoData().getBdName()) ? "" : returnVo.getInfoData().getBdName();
            zdName = StringUtils.isBlank(returnVo.getInfoData().getZdName()) ? "" : returnVo.getInfoData().getZdName();
            htdName = bdName + zdName;
            detailList = returnVo.getDetailList();
        }
        List<MaMaterialPlanDetailsExportVo> data = new ArrayList<>();
        String finalDeptName = deptName;
        final int[] index = {1};
        detailList.forEach(item -> {
            MaMaterialPlanDetailsExportVo bean = BeanUtil.toBean(item, MaMaterialPlanDetailsExportVo.class);
            bean.setXuh(index[0]);
            bean.setDeptName(finalDeptName);
            data.add(bean);
            index[0]++;
        });
        Map<String, String> map = new HashMap<>();
        map.put("htdName", htdName);
        map.put("weaveDate", weaveDate);
        ExcelUtil.exportTemplate(CollUtil.newArrayList(map, data), "甲供材月度需求计划表.xlsx", "excel/甲供材月度需求计划表.xlsx", response);
    }

    /**
     * 获取材料计划详细信息
     *
     * @param planId 主键
     */
    @SaCheckLogin
    @GetMapping("/{planId}")
    public R<MaMaterialPlanVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long planId) {
        return R.ok(iMaMaterialPlanService.queryById(planId));
    }

    /**
     * 新增材料计划
     */
    @SaCheckLogin
    @Log(title = "材料计划", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody MaMaterialPlanBo bo) {
        return toAjax(iMaMaterialPlanService.insertByBo(bo));
    }

    /**
     * 修改材料计划
     */
    @SaCheckLogin
    @Log(title = "材料计划", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody MaMaterialPlanBo bo) {
        return toAjax(iMaMaterialPlanService.updateByBo(bo));
    }

    /**
     * 删除材料计划
     *
     * @param planIds 主键串
     */
    @SaCheckLogin
    @Log(title = "材料计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{planIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] planIds) {
        return toAjax(iMaMaterialPlanService.deleteWithValidByIds(Arrays.asList(planIds), true));
    }

    /**
     * 获取明细
     *
     * @param planId 主键
     */
    @SaCheckLogin
    @GetMapping("/getDetails/{planId}")
    public R<MaMaterialPlanDataDetailsReturnVo> getDetails(@NotNull(message = "主键不能为空")
                                       @PathVariable Long planId) {
        return R.ok(iMaMaterialPlanService.getDetails(planId));
    }

}
